package com.aoip.telemetry.telemetry.receive.handler;

import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import io.netty.handler.ipfilter.IpFilterRule;
import io.netty.handler.ipfilter.IpFilterRuleType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @Description TODO
 * @date 2023/6/6 22:56
 */
@Component
@Slf4j
public class IpFilterRuleHandler implements IpFilterRule {
    @Resource
    private RedisCache redisCache;

    @Override
    public boolean matches(InetSocketAddress remoteAddress) {
        //ip转成long类型
        String ip = remoteAddress.getHostString();
        List<String> blackIpList = redisCache.getCacheObject(CacheKeyEnum.BLACK_ST_CODE_LIST.getCode());
        return blackIpList.contains(ip);
//        long ipLong = NetWorkUtil.ipToLong(ip);
//
//        //创建一个要过滤的ip段
//        IpRange ipRange = new IpRange("172.31.1.81", "172.31.1.87");
//
//        long ipStart = NetWorkUtil.ipToLong(ipRange.getIpStart());
//        long ipEnd = NetWorkUtil.ipToLong(ipRange.getIpEnd());
        //比较ip区间
//        if (ipLong >= ipStart && ipLong <= ipEnd) {
//            //返回true则执行过滤器
//            return true;
//        }
//        //返回false表示不执行过滤器
//        return false;

    }

    @Override
    public IpFilterRuleType ruleType() {
        //返回拒绝则表示拒绝连接，反之返回接受则表示可以连接
        return IpFilterRuleType.REJECT;
    }
}
